package com.harmony.volley.sample.ui.slice;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpClientStack;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.Volley;
import com.google.gson.reflect.TypeToken;
import com.harmony.volley.sample.Constant;
import com.harmony.volley.sample.ResourceTable;
import com.harmony.volley.sample.model.HomeArticleModel;
import com.harmony.volley.sample.ui.itemprovider.HomeArticleItemViewBinder;
import com.harmony.volley.sample.util.ToastUtil;
import com.harmony.volley.sample.volley.JacksonRequest;
import com.zh.harmony.volley.asynchttpclientstack.AsyncHttpClientStack;
import com.zh.harmony.volley.okhttpstack.OkHttpStack;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import me.drakeet.multitype.MultiTypeAdapter;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Home
 */
public class HomeSlice extends AbilitySlice {
    public static final String KEY_TYPE = "KEY_TYPE";

    public static final int TYPE_HTTP_URL_CONNECTION = 1;
    public static final int TYPE_HTTP_CLIENT = 2;
    public static final int TYPE_OKHTTP = 3;
    public static final int TYPE_ASYNC_HTTP_CLIENT = 4;

    private ListContainer vList;
    private final List<HomeArticleModel.PageModel.ItemModel> mListData = new ArrayList<>();
    private final MultiTypeAdapter mListAdapter = new MultiTypeAdapter(mListData);

    /**
     * 请求队列
     */
    private RequestQueue mRequestQueue;
    /**
     * 当前页码
     */
    private int mCurrentPage;
    /**
     * 是否有下一页
     */
    private boolean hasMore = true;

    public static void start(AbilitySlice abilitySlice, int type) {
        Intent intent = new Intent();
        intent.setParam(HomeSlice.KEY_TYPE, type);
        abilitySlice.present(new HomeSlice(), intent);
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_home);
        findView();
        bindView();
        initVolley(intent);
        setData();
    }

    private void findView() {
        vList = (ListContainer) findComponentById(ResourceTable.Id_list);
    }

    private void bindView() {
        //设置适配器
        vList.setItemProvider(mListAdapter);
        //注册条目类型
        mListAdapter.register(HomeArticleModel.PageModel.ItemModel.class, new HomeArticleItemViewBinder());
        //设置点击事件
        vList.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int position, long id) {
                HomeArticleModel.PageModel.ItemModel itemModel = mListData.get(position);
                String link = itemModel.getLink();
                //点击跳转到浏览器
                Intent intent = new Intent();
                intent.setParam(Constant.KEY_WEB_LINK, link);
                present(WebSlice.newInstance(), intent);
            }
        });
        //设置滚动监听，滚动结束后回调
        vList.setScrollListener(new ListContainer.ScrollListener() {
            @Override
            public void onScrollFinished() {
                //没有下一页
                if (!hasMore) {
                    return;
                }
                int lastVisibleItemPosition = vList.getLastVisibleItemPosition();
                if (lastVisibleItemPosition == mListData.size() - 1) {
                    //加载更多
                    loadMore();
                }
            }
        });
    }

    private void initVolley(Intent intent) {
        int type = intent.getIntParam(KEY_TYPE, TYPE_HTTP_URL_CONNECTION);
        //创建请求队列
        if (type == TYPE_HTTP_URL_CONNECTION) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack());
        } else if (type == TYPE_HTTP_CLIENT) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new HttpClientStack(new DefaultHttpClient()));
        } else if (type == TYPE_OKHTTP) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new OkHttpStack());
        } else if (type == TYPE_ASYNC_HTTP_CLIENT) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new AsyncHttpClientStack());
        } else {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack());
        }
    }

    private void setData() {
        refresh();
    }

    private void refresh() {
        this.mCurrentPage = 0;
        getHomeArticle(mCurrentPage, true);
    }

    private void loadMore() {
        int nextPage = this.mCurrentPage + 1;
        getHomeArticle(nextPage, false);
    }

    /**
     * 获取首页文章列表
     */
    private void getHomeArticle(int page, boolean isRefresh) {
        String url = "https://www.wanandroid.com/article/list/" + page + "/json";
        Type type = new TypeToken<HomeArticleModel>() {
        }.getType();

        //创建请求，设置回调
        Request<HomeArticleModel> request = new JacksonRequest<>(url, type, new Response.Listener<HomeArticleModel>() {
            @Override
            public void onResponse(HomeArticleModel response) {
                processResult(response, isRefresh);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                ToastUtil.toast(getContext(), "请求失败：" + error.getMessage());
            }
        });
        //加入队列，发起请求
        mRequestQueue.add(request);
    }

    private void processResult(HomeArticleModel model, Boolean isRefresh) {
        if (model == null) {
            return;
        }
        HomeArticleModel.PageModel pageModel = model.getData();
        List<HomeArticleModel.PageModel.ItemModel> list;
        if (pageModel.getDatas() != null) {
            list = pageModel.getDatas();
        } else {
            list = new ArrayList<>();
        }
        //是否有下一页
        hasMore = !pageModel.isOver();
        //更新当前页码
        mCurrentPage = pageModel.getOffset();
        if (isRefresh) {
            mListData.clear();
        }
        //更新列表
        mListData.addAll(list);
        mListAdapter.notifyDataChanged();
    }
}